//Crackign coding interview, 13.1
//Pring last K lines of a file
//11:20AM--11:27AM--

#include<fstream>
#include<string>
#include<vector>
#include<iostream>
#include<sstream>
#include<cstdlib>

#define MAX_LINE 10000

using namespace std;



void PrintKLines(string filename, int K) {
	if(K<1) return;
	
	ifstream fs(filename.c_str(), fstream::in);
	vector<string> strArray(K);
	int index=0;
	while(fs.good()) {
		getline(fs, strArray[index]);
		index=(index+1)% K;
	}
	// useless codes
	bool t=fs.eof();


	fs.close();
	for(int i=0; i<K; i++) {
		cout<<i<<":\t"<<strArray[index].c_str()<<endl;
		index=(index+1) % K;
	}
}

void PrintKLinesC(string filename, int K) {
	if(K<1) return;
	
	FILE *fp=fopen(filename.c_str(), "r");
	vector<string> strArray(K);

	int index=0;
	char buf[MAX_LINE];
	stringstream ss;
	if(fp) {
		while (fgets(buf, MAX_LINE, fp)) {
			if(strlen(buf)<MAX_LINE) {
				strArray[index]=ss.str();
				int a=strArray[index].size();
				strArray[index]+=buf;
				string ts(buf);
				int b=strArray[index].size();
				index=(index+1) % K;
				ss.clear();
			} else {
				ss<<buf;		//'\0'?
			}
		}

		for(int i=0; i<K; i++) {
			cout<<i<<":\t"<<strArray[index].c_str();
			index=(index+1) % K;
		}
	}

	fclose(fp);
}

int main(int argc, char *argv[]) {
	string filename("D:\\Research\\Code\\algorithmpractice\\graph_algorithm.cc");
	PrintKLinesC(filename, 5);
	return 0;
}